/**
 * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.employee.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.google.common.collect.Lists;
import com.thinkgem.jeesite.common.beanvalidator.BeanValidators;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.utils.excel.ExportExcel;
import com.thinkgem.jeesite.common.utils.excel.ImportExcel;
import com.thinkgem.jeesite.modules.employee.entity.EmployeeLeave;
import com.thinkgem.jeesite.modules.employee.service.EmployeeLeaveService;
import com.thinkgem.jeesite.modules.employee.service.EmployeeService;

/**
 * 员工假期Controller
 * @author hui.li
 * @version 2017-07-18
 */
@Controller
@RequestMapping(value = "${adminPath}/employee/employeeLeave")
public class EmployeeLeaveController extends BaseController {

	@Autowired
	private EmployeeLeaveService employeeLeaveService;
	@Autowired
	private EmployeeService employeeService;
	@ModelAttribute
	public EmployeeLeave get(@RequestParam(required=false) String id) {
		EmployeeLeave entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = employeeLeaveService.get(id);
		}
		if (entity == null){
			entity = new EmployeeLeave();
		}
		return entity;
	}
	
	@RequiresPermissions("employee:employeeLeave:view")
	@RequestMapping(value = {"list", ""})
	public String list(EmployeeLeave employeeLeave, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<EmployeeLeave> page = employeeLeaveService.findPage(new Page<EmployeeLeave>(request, response), employeeLeave); 
		model.addAttribute("page", page);
		return "modules/employee/employeeLeaveList";
	}

	@RequiresPermissions("employee:employeeLeave:view")
	@RequestMapping(value = "form")
	public String form(EmployeeLeave employeeLeave, Model model) {
		model.addAttribute("employeeLeave", employeeLeave);
		return "modules/employee/employeeLeaveForm";
	}

	@RequiresPermissions("employee:employeeLeave:edit")
	@RequestMapping(value = "save")
	public String save(EmployeeLeave employeeLeave, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, employeeLeave)){
			return form(employeeLeave, model);
		}
		employeeLeaveService.save(employeeLeave);
		addMessage(redirectAttributes, "保存员工假期成功");
		return "redirect:"+Global.getAdminPath()+"/employee/employeeLeave/?repage";
	}
	
	@RequiresPermissions("employee:employeeLeave:edit")
	@RequestMapping(value = "delete")
	public String delete(EmployeeLeave employeeLeave, RedirectAttributes redirectAttributes) {
		employeeLeaveService.delete(employeeLeave);
		addMessage(redirectAttributes, "删除员工假期成功");
		return "redirect:"+Global.getAdminPath()+"/employee/employeeLeave/?repage";
	}

	/**
	 * 导出员工假期数据
	 * @param EmployeeLeave
	 * @param request
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("employee:employeeLeave:view")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(EmployeeLeave employeeLeave, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "员工假期信息数据"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<EmployeeLeave> page = employeeLeaveService.findPage(new Page<EmployeeLeave>(request, response, -1), employeeLeave);
    		new ExportExcel("员工假期信息数据", EmployeeLeave.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出员工假期失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/employee/employeeLeave/list?repage";
    }
	/**
	 * 导入用户假期数据
	 * @param file
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("employee:employeeLeave:edit")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		if(Global.isDemoMode()){
			addMessage(redirectAttributes, "演示模式，不允许操作！");
			return "redirect:" + adminPath + "/employee/employeeLeave/list?repage";
		}
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 0, 0);
			List<EmployeeLeave> list = ei.getDataList(EmployeeLeave.class);
			for (EmployeeLeave employeeLeave : list){
				try{
					if ("true".equals(employeeService.getcheckEmployeeNumber(employeeLeave.getEmployeeNumber()))){
						failureMsg.append("<br/>工号 "+employeeLeave.getEmployeeNumber()+" 员工工号不存在; ");
						failureNum++;
					}else{
						employeeLeaveService.save(employeeLeave);
						successNum++;
					}
				}catch(ConstraintViolationException ex){
					failureMsg.append("<br/>工号 "+employeeLeave.getEmployeeNumber()+" 导入失败：");
					List<String> messageList = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");
					for (String message : messageList){
						failureMsg.append(message+"; ");
						failureNum++;
					}
				}catch (Exception ex) {
					failureMsg.append("<br/>工号 "+employeeLeave.getEmployeeNumber()+" 导入失败："+ex.getMessage());
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条员工，导入信息如下：");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条员工"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入员工假期失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/employee/employeeLeave/list?repage";
    }
	
	/**
	 * 下载导入用户数据模板
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("employee:employeeLeave:edit")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "员工假期数据导入模板.xlsx";
    		List<EmployeeLeave> list = Lists.newArrayList();
    		new ExportExcel("", EmployeeLeave.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/employee/employeeLeave/list?repage";
    }

}